package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dtos.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.ex.CustomerException;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ghy
 * @version v1.0
 * create on 2022/11/21 17:17
 */
@Service
@Slf4j
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {
    /**
     * 登录
     * @param dto 登录Dto
     * @param code 发送的验证码
     * @return
     */
    @Override
    public Long login(LoginDto dto, String code) {
        //1.比对验证码
        if(StringUtils.isBlank(code)) {
            throw new CustomerException("验证码异常！");
        }
        if(!code.equals(dto.getCode())) {
            throw new CustomerException("验证码有误！");
        }
        //2.登录：根据手机号查询
        User user = this.getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, dto.getPhone() ));
        //2.1 没有用户：直接给你开通
        if(user == null) {
            user = new User();
            user.setPhone(dto.getPhone());
            user.setStatus(1);
            this.save(user);
        }
        //2.2登录
        return user.getId();
    }
}
